#include "../include/LoopThread.h"
#include "../include/EventLoop.h"

/*实例化EventLoop对象，唤醒_cond上有可能阻塞的线程，并开始运行EventLoop模块的功能*/
void LoopThread::ThreadEntry()
{
    // NOTE: This creates a memory leak.
    // A proper implementation would require a shutdown mechanism to signal the loop
    // to quit, allowing the thread to be joined and memory to be safely freed.
    // EventLoop *loop = new EventLoop();
    EventLoop loop;
    {
        std::unique_lock<std::mutex> lock(_mutex);
        _loop = &loop;
        _cond.notify_all();
    }
    loop.Start();
}

LoopThread::LoopThread() : _loop(nullptr), _thread(std::thread(&LoopThread::ThreadEntry, this)) {}

LoopThread::~LoopThread()
{
    if (_thread.joinable())
    {
        _thread.detach();
    }
}

EventLoop *LoopThread::getLoop()
{
    EventLoop *loop = nullptr;
    {
        std::unique_lock<std::mutex> lock(_mutex);
        // 一直获取直到_loop非空,防止返回空指针解引用崩溃
        _cond.wait(lock, [&]()
                   { return _loop != nullptr; });
        loop = _loop;
    }
    return loop;
}
